package com.Spring.SpringSpms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import com.Spring.SpringSpms.model.PlatForm;

public class PlatFormDAOImpl implements PlatFormDAO {

	private JdbcTemplate jdbcTemplate;
	
	
	public PlatFormDAOImpl(DataSource dataSource)
	{
		this.jdbcTemplate=new JdbcTemplate(dataSource);
	}
	@Override
	public void saveOrUpdate(PlatForm platform) {
		// TODO Auto-generated method stub

		
		if (platform.getPlatFormid() > 0) {
			// update
			String sql = "UPDATE platform SET platform_name=?, platform_description=? WHERE platform_id=?";
			jdbcTemplate.update(sql,platform.getPlatFormName(),platform.getPlatFormDescription(),platform.getPlatFormid());
		} else {
			// insert
			String sql = "INSERT INTO platForm (platform_name, platform_description)"
						+ " VALUES (?, ?)";
			jdbcTemplate.update(sql,platform.getPlatFormName(),platform.getPlatFormDescription());
		}


	}

	@Override
	public void delete(int platformId) {
		// TODO Auto-generated method stub

		String sql = "DELETE FROM platform WHERE platform_id=?";
		jdbcTemplate.update(sql,platformId);

	}

	@Override
	public PlatForm get(int platformId) {
		// TODO Auto-generated method stub
		String sql = "SELECT * FROM platform WHERE platform_id=" + platformId;
		return jdbcTemplate.query(sql, new ResultSetExtractor<PlatForm>() {

			@Override
			public PlatForm extractData(ResultSet rs) throws SQLException,
					DataAccessException {
				if (rs.next()) {
					PlatForm platForm=new PlatForm();
					platForm.setPlatFormid(rs.getInt("platform_id"));
					platForm.setPlatFormName(rs.getString("platform_name"));
					platForm.setPlatFormDescription(rs.getString("platform_description"));
					return platForm;
				
				}
				
				return null;
			}
			
		});

	}

	@Override
	public List<PlatForm> list() {
		// TODO Auto-generated method stub
		String sql = "SELECT * FROM platform";
		List<PlatForm> listPlatform = jdbcTemplate.query(sql, new RowMapper<PlatForm>() {

			@Override
			public PlatForm mapRow(ResultSet rs, int rowNum) throws SQLException {
				PlatForm aPlatform = new PlatForm();
	
				aPlatform.setPlatFormid(rs.getInt("platform_id"));
				aPlatform.setPlatFormName(rs.getString("platform_name"));
				aPlatform.setPlatFormDescription(rs.getString("platform_description"));
				return aPlatform;
			}
			
		});
		
		return listPlatform;
	}

	}

